package com.mtconnect.util;

import com.mtconnect.dao.InitDB;
import com.mtconnect.exception.DAOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017/9/5.
 */
public class Sequence {

    private static final Logger LOGGER = LoggerFactory.getLogger(Sequence.class);

    /**
     * 获取empress数据库当前的sequence值
     *
     * @return 返回数据库中当前的sequence值
     */
    public static long getCurrSeqVal() {
        long val = -1;
        try (InitDB initDB = new InitDB()) {
            List<String> allTable = initDB.getAllTable();
            for (int i = 0; i < allTable.size(); i++) {
                PreparedStatement statement = initDB.getConnection().prepareStatement("SELECT * FROM '" + allTable.get(i) + "'");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    long sequence = resultSet.getLong("sequence");
                    if (sequence > val) {
                        val = sequence;
                    }
                    break;
                }
                resultSet.close();
                statement.close();
            }
            LOGGER.debug("sequence current value is {}", val);
        } catch (DAOException e) {
            LOGGER.error("Object InitDB initialize failed", e);
        } catch (SQLException e) {
            LOGGER.error("statement or resultSet exception", e);
        }
        return val;
    }
}
